package org.erepublik.company.scanner;


import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;

import org.erepublik.company.ECountry;
import org.erepublik.company.EProductType;
import org.erepublik.company.comparators.ProductComparatorByPriceInGold;
import org.erepublik.company.product.Product;
import org.erepublik.company.product.ProductDesign;
import org.erepublik.company.product.ProductKey;
import org.erepublik.company.product.Raw;
import org.erepublik.company.service.ICompanyCountryService;
import org.erepublik.company.service.IVatService;
import org.erepublik.company.service.InternetCompanyCountryService;
import org.erepublik.company.service.JSONExchangeRateService;
import org.erepublik.company.service.XmlVatService;

public class RawScanner extends ProductScanner<Raw> {

    @Override
    protected Raw[] getEmptyTable() {
        return new Raw[0];
    }

    private Raw scannedProduct = null;
    @Override
    protected Raw getNewProduct() {
        return scannedProduct.clone();
    }

    @Override
    protected Raw[] getProductsFromCountry(ECountry country, IVatService vatService, ICompanyCountryService companyService,
            JSONExchangeRateService currency) throws Exception {


        HashMap<ProductKey, Product> map = new HashMap<ProductKey, Product>();

        EProductType[] raws = new EProductType[] { EProductType.IRON, EProductType.GRAIN, EProductType.OIL, EProductType.STONE, EProductType.TITANIUM };
        for (EProductType eProductType : raws) {
            scannedProduct = new Raw(eProductType);
            Product[] scannedProducts = getProductList(country, new ProductDesign(eProductType), vatService, companyService, currency);
            for (Product product : scannedProducts) {
                ProductKey key = new ProductKey(product.getCompanyOwner().getId(), country);
                if (!map.containsKey(product)) {
                    map.put(key, product);
                }
            }
        }

        Raw[] products = map.values().toArray(new Raw[0]);
        Arrays.sort(products, new ProductComparatorByPriceInGold());
        
        return products;
    }

    
    public static void main(String[] args) throws Exception {
        RawScanner rawScanner = new RawScanner();
        DecimalFormat decimalFormatter = new DecimalFormat("##0.0######");
        Raw[] raws = rawScanner.getProductsFromAllCountries(new XmlVatService(), new InternetCompanyCountryService(), new JSONExchangeRateService());
        Arrays.sort(raws, new ProductComparatorByPriceInGold());
        for (Raw raw : raws) {
            System.out.println( raw.getCountry() + " " +  decimalFormatter.format( raw.getPriceInGold() )+"g "+raw.getProductType() + " "+raw.getQuantity());
        }
    }
    
}
